package com.chunuo.commonbase.syslog;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 切面编程：
 *          所有访问controller的相关信息都会写进日志里
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-07-04 17:12
 */
@Component
@Aspect
@Slf4j

public class SysLogger {

    //执行哪个地址下
    @Pointcut("execution(* com.chunuo.*.controller.*.*(..))")
    public void log(){}

    @Before("log()")
    public void before(JoinPoint point){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //链接
        String url = request.getRequestURL().toString();
        //ip
        String ip = request.getRemoteAddr();
        //类名和方法名
        String classMethod =  point.getSignature().getDeclaringTypeName()+"."+point.getSignature().getName();
        //参数
        Object[] args = point.getArgs();
        //封装到对象中
        RequestLog requestLog = new RequestLog(ip,url,classMethod,args);
        //写入文件
        log.info("request : {}",requestLog);
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void afterReturn(Object result){
        log.info("Result : {}",result);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private class RequestLog{
        String ip;
        String url;
        String method;
        Object[] args;
    }


}
